package com.xiguthings.waka.shiro.realm;

import com.xiguthings.waka.shiro.CustomizedToken;
import com.xiguthings.waka.web.controller.wechat.wx.WxConnExec;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.HashMap;
import java.util.Map;


public class UserAuthRealm extends AuthorizingRealm {


//	public List<String> getPermission(String account) {
//		List<String> list = new ArrayList<String>(0);
//		String sql = "SELECT res.RES_URL FROM (sys_resource res RIGHT JOIN (SELECT * FROM sys_role_res roleres RIGHT JOIN (SELECT ROLE_ID roleid from ((SELECT `user`.user_id from sys_user user where `user`.ACCOUNT = ? ) tmpuser LEFT JOIN sys_user_role userrole ON tmpuser.user_id = userrole.USER_ID)) tmp ON tmp.roleid = roleres.ROLE_ID) rr ON res.RES_ID = rr.res_id) where res.RES_URL is not null";
//		Object[] param = new Object[] { account };
//		List<SysResourceEntity> resEntitys = jdbcTemplate.queryForObjectList(sql, param, SysResourceEntity.class);
//		for (SysResourceEntity res : resEntitys) {
//			list.add(res.getResUrl());
//		}
//		return list;
//	}

//	public List<SysUserEntity> findByAccount(String account) {
//		String sql = "SELECT * FROM sys_user where ACCOUNT = ?";
//		List<SysUserEntity> list = jdbcTemplate.queryForObjectList(sql, new Object[] { account }, SysUserEntity.class);
//		return list;
//	}

//	private List<String> getAllPermission() {
//		List<String> list = new ArrayList<String>(0);
//		String sql = "SELECT RES_URL FROM sys_resource ";
//		Object[] param = new Object[] {};
//		List<SysResourceEntity> resEntitys = jdbcTemplate.queryForObjectList(sql, param, SysResourceEntity.class);
//		for (SysResourceEntity res : resEntitys) {
//			list.add(res.getResUrl());
//		}
//		return list;
//	}

    /**
     * 授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        // 获取登录用户的权限，配合jsp页面中的shiro标签进行控制
//		SysUserEntity curUser = (SysUserEntity) principals.fromRealm(getName()).iterator().next();
//		String account = curUser.getAccount();
//		List<String> sList = null;
//		if (account.equals("admin")) {
//			sList = this.getAllPermission();
//		} else {
//			sList = this.getPermission(account);
//		}
//		System.out.println("获得的权限："+sList);
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
//		if (sList != null && sList.size() > 0) {
//			for (String permission : sList) {
//				// 设置当前用户的权限
//				authorizationInfo.addStringPermission(permission);
//			}
//		} else {
//			authorizationInfo.addStringPermission("0");
//		}
        return authorizationInfo;
    }

    /**
     * 认证 登录
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {


        // 1.向下转型
        CustomizedToken upToken = (CustomizedToken) token;
        String loginCode = upToken.getLoginCode();
        if (StringUtils.isNotBlank(loginCode)) {
            String openid = null;
            try {
                openid = WxConnExec.xcxGetOpenid(loginCode);
            } catch (Exception e) {
                e.printStackTrace();
//                openid = "openid1";
                return null;// 就会出现异常
            }
            if (StringUtils.isNotBlank(openid)) {
                Map<String, Object> map = new HashMap<>();
                map.put("openid", openid);
                upToken.setParam(map);
                AuthenticationInfo info = new SimpleAuthenticationInfo("", "", this.getName());
                return info; // 此处如果返回，就会立即进入到密码比较器
            }
        }
        return null;// 就会出现异常
    }

}
